package shelly.basic.class03;

import shelly.Util;
import shelly.common.Node;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: Shelly
 * @create: 2023-01-26 13:49:02
 * @describe: 在链表中删除指定值的所有节点
 */
public class Code02_DeleteGivenValue {
    public static Node deleteGivenValue(Node head, int num){
        while(head != null){
            if (head.value == num){
                head = head.next;
            }else{
                break;
            }
        }
        Node pre = head;
        Node cur = head;
        while(cur != null){
            if (cur.value == num) {
                pre.next = cur.next;
            }else{
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }

    // 对数器：List
    public static List<Integer> testDeleteGivenValue(Node head,int num){
        List<Integer> list = new ArrayList<>();
        while (head != null){
            if (head.value != num){
                list.add(head.value);
            }
            head = head.next;
        }
        return list;
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        int lenth = 5;
        int value = 5;
        int times = 10;
        System.out.println("******* begin **************");
        while (times >= 0){
            Node node = Util.generateRandomLinkedList(lenth,value);
            List<Integer> list1 = Util.getLinkedListOriginOrder(node);// 原
            List<Integer> list = testDeleteGivenValue(node,2); // test
            Node n1 = deleteGivenValue(node,2);//
            if(!Util.checkLinkedListAndNode(list,n1)){
                System.out.println("oops!");
                System.out.println("//////before///////////");
                Util.printLinkedList(list1);
                System.out.println("//////after///////////");
                List<Integer> list2 = Util.getLinkedListOriginOrder(n1);
                Util.printLinkedList(list2);
                System.out.println("//////linkedlist///////////");
                Util.printLinkedList(list);
            }
            times--;
        }
        System.out.println("******* end **************");
    }
}
